package com.hmall.trade.listener;

import com.hmall.api.domain.dto.OrderMsgDTO;

import com.hmall.cart.service.ICartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.core.Message;

@Slf4j
@Configuration
public class OrderCreateListener {

    @Autowired
    private ICartService cartService;
    
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "cart.clear.queue", durable = "true"),
            exchange = @Exchange(name = "trade.topic", type = ExchangeTypes.TOPIC),
            key = "order.create"
    ), ackMode = "MANUAL") // 手动确认模式
    public void listenerOrderCreate(OrderMsgDTO msgDTO, Message message) {
        log.info("接收到订单创建的消息，用户ID:{},商品ID:{}", msgDTO.getUserId(), msgDTO.getItemIds());
        try {
            cartService.removeByItemIds(msgDTO.getItemIds());
            log.info("购物车清理成功");
            // 手动确认消息
            rabbitTemplate.execute(channel -> {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return null;
            });
        } catch (Exception e) {
            log.error("购物车清理失败", e);
            try {
                // 拒绝消息并重新入队，最多重试3次
                rabbitTemplate.execute(channel -> {
                    // 检查重试次数
                    Integer retryCount = (Integer) message.getMessageProperties().getHeaders().getOrDefault("retry-count", 0);
                    if (retryCount < 3) {
                        // 重新入队并增加重试次数
                        message.getMessageProperties().getHeaders().put("retry-count", retryCount + 1);
                        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                    } else {
                        // 达到最大重试次数，不再重新入队
                        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
                        log.error("消息处理失败达到最大重试次数，消息将被丢弃，用户ID:{},商品ID:{}", msgDTO.getUserId(), msgDTO.getItemIds());
                    }
                    return null;
                });
            } catch (Exception ex) {
                log.error("消息确认失败", ex);
            }
        }
    }
}
